

import wx
from socket import *
import threading

class Client(wx.Frame):
    def __init__(self):

        # 实例属性
        self.name = "user1"
        self.isConnected = False
        self.clinet_socket = None
        wx.Frame.__init__(self,None,title=self.name+"多人聊天室",size=(450,660),pos=(100,100))
        # 页面布局

        self.pl = wx.Panel(self)

        # 按钮
        self.btn_enter = wx.Button(self.pl,label="加入聊天室",pos=(10,10),size=(200,40))
        self.btn_leave = wx.Button(self.pl,label="离开聊天室",pos=(220,10),size=(200,40))
        self.btn_send = wx.Button(self.pl,label="发送",pos=(10,580),size=(200,40))
        self.btn_clear = wx.Button(self.pl,label="清空文本",pos=(220,580),size=(200,40))

        # 文本框
        self.text_message = wx.TextCtrl(self.pl,size=(400,400),pos=(10,60),style=wx.TE_READONLY | wx.TE_MULTILINE)
        self.text_input = wx.TextCtrl(self.pl,size=(400,100),pos=(10,470),style= wx.TE_MULTILINE)

        # 按钮事件绑定
        self.Bind(wx.EVT_BUTTON,self.enter,self.btn_enter)
        self.Bind(wx.EVT_BUTTON,self.leave,self.btn_leave)
        self.Bind(wx.EVT_BUTTON,self.send,self.btn_send)
        self.Bind(wx.EVT_BUTTON,self.clear,self.btn_clear)

    # 点击安按钮回调
    def enter(self,event):
        print("enter")
        if self.isConnected == False:
            self.isConnected = True
            self.client_socket = socket()
            self.client_socket.connect(('127.0.0.1', 8999))
            # 发送用户名
            self.client_socket.send(self.name.encode('utf8'))

            # 创建接收消息的子进程
            main_thread = threading.Thread(target=self.recv_data)
            main_thread.daemon = True
            main_thread.start()

    def leave(self,event):
        print("leave")
        self.client_socket.send('断开连接'.encode('utf8'))
        self.isConnected = False

    def send(self,event):
        print("send")
        if self.isConnected:
            text = self.text_input.GetValue()
            if text != '':
                self.client_socket.send(text.encode('utf8'))
                self.text_input.Clear()

    def clear(self,event):
        print("clear")
        self.text_input.Clear()

    def recv_data(self):
        print("监听消息子进程已启动")
        while self.isConnected:

            text = self.client_socket.recv(1024).decode('utf8')
            print("获取到消息",text)
            self.text_message.AppendText(text+'\n')


if __name__ == "__main__":
    # 创建应用对象
    app = wx.App()
    # 创建客户端窗口
    client = Client()
    # 显示
    client.Show()
    # 显示
    app.MainLoop()